package com.udf.hive.udf;

import org.apache.hadoop.hive.ql.exec.UDF;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

public class FromTimstampMS  extends UDF {
    private final String defaultTimeFormater = "yyyy-MM-dd HH:mm:ss.SSS";

    public String evaluate(String timeStampMs, String input) {
        Instant instant = Instant.ofEpochMilli(Long.parseLong(timeStampMs));
        if (input != null && !input.trim().isEmpty()) {
            return LocalDateTime.ofInstant(instant, ZoneId.systemDefault()).format(DateTimeFormatter.ofPattern(input));
        } else {
            return LocalDateTime.ofInstant(instant, ZoneId.systemDefault()).format(DateTimeFormatter.ofPattern(defaultTimeFormater));
        }
    }

    public String evaluate(long timeStampMs, String input) {
        Instant instant = Instant.ofEpochMilli(timeStampMs);
        if (input != null && !input.trim().isEmpty()) {
            return LocalDateTime.ofInstant(instant, ZoneId.systemDefault()).format(DateTimeFormatter.ofPattern(input));
        } else {
            return LocalDateTime.ofInstant(instant, ZoneId.systemDefault()).format(DateTimeFormatter.ofPattern(defaultTimeFormater));
        }
    }

    public String evaluate(long timeStampMs) {
        Instant instant = Instant.ofEpochMilli(timeStampMs);
        return LocalDateTime.ofInstant(instant, ZoneId.systemDefault()).format(DateTimeFormatter.ofPattern(defaultTimeFormater));
    }
    public String evaluate(String timeStampMs) {
        Instant instant = Instant.ofEpochMilli(Long.parseLong(timeStampMs));
        return LocalDateTime.ofInstant(instant, ZoneId.systemDefault()).format(DateTimeFormatter.ofPattern(defaultTimeFormater));
    }
}
